package com.xin.util;

import sun.misc.BASE64Decoder;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * created by l1 on 2017/11/27.
 */
public class DecryptionUtil {

    public static String desc(String desc,String key,String secret){
        String originalString = null;
        try {
            secret = secret.substring(0,16);
            String strEncryptWno = unescape(desc); //获取到的密文，先转码后再解密
            byte[] raw = key.getBytes("UTF-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

            IvParameterSpec iv = new IvParameterSpec(secret.getBytes("UTF-8"));
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);

            byte[] strTmpEncrypted = new BASE64Decoder().decodeBuffer(strEncryptWno);//先用base64解密

            byte[] original = cipher.doFinal(strTmpEncrypted);
            originalString = new String(original, "UTF-8");

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return originalString;
    }

    public String encry(String encry,String key,String secret){
        return null;
    }
    //转码方法
    private static String unescape(String src) {
        StringBuffer tmp = new StringBuffer();
        tmp.ensureCapacity(src.length());
        int lastPos = 0, pos = 0;
        char ch;
        while (lastPos < src.length()) {
            pos = src.indexOf("%", lastPos);
            if (pos == lastPos) {
                if (src.charAt(pos + 1) == 'u') {
                    ch = (char) Integer.parseInt(src
                            .substring(pos + 2, pos + 6), 16);
                    tmp.append(ch);
                    lastPos = pos + 6;
                } else {
                    ch = (char) Integer.parseInt(src
                            .substring(pos + 1, pos + 3), 16);
                    tmp.append(ch);
                    lastPos = pos + 3;
                }
            } else {
                if (pos == -1) {
                    tmp.append(src.substring(lastPos));
                    lastPos = src.length();
                } else {
                    tmp.append(src.substring(lastPos, pos));
                    lastPos = pos;
                }
            }
        }
        return tmp.toString();
    }
}
